 var appRoot = new Vue({
	el:'.container',
	data:function(){
     	
     	var v_pwd1 = (rule, value, callback) => {
	        if (value === '') {
	          	callback(new Error('请输入密码'));
	        } else if(value && value.length < 6){
	        	callback(new Error('至少6是个字符'));
	        }else {
	          	if (this.user_data.CK_PWD !== '') {
		            this.$refs.user_form.validateField('CK_PWD');
		        }
	        	callback();
	    	}
	   	};
		   	
	 	var v_pwd2 =  (rule, value, callback) => {
	    	if (value === '') {
	          	callback(new Error('请再次输入密码'));
	        } else if (value !== this.user_data.PWD) {
	          	callback(new Error('两次输入密码不一致!'));
	        } else {
	          	callback();
	        }
		}
     
     	return {
             appctx:_AppRootContext,
             apps:[],
             all_apps:[],
             active_mode:'me',
             ld_user_url:"{0}/user/getUser?lx=2".format(_AppRootContext),
             ld_user_url_:"{0}/user/getUser".format(_AppRootContext),                        		
             user_lx_options:[
            		{label:'全部',value:'2'},
            		{label:'教师',value:'1'},
            		{label:'学生',value:'0'}
             ],
             user_search:{
             	kw:'',
             	lx:"2"
             },
            	// 用户管理
             user_show:false,
             user_optype:1,
        	user_data:{},
        	op_posting:false,
        	reset_pwd_show:false,
        	reset_pwd_data:{
        		userId:'',
        		pwd:'',
        		n_pwd:''
        	},
        	reset_pwd_rules:{
        		userId:[
        			{ required: true, message: '请输入学号职工号', trigger: 'blur' }
        		],
        		pwd: [
        			{ required: true, message: '请输入密码', trigger: 'blur' },
        			{ min: 6, message: '至少6个字符', trigger: 'blur' }
        		]
        	},
        	user_rules:{
        		XH: [
                 { required: true, message: '请输入学号职工号', trigger: 'blur' },
                 { min: 4, message: '至少4个字符', trigger: 'blur' }
        		],
        		XM: [
                 { required: true, message: '请输入姓名', trigger: 'blur' }
        		],
        		LX: [
                 { required: true, message: '选择用户类型', trigger: 'blur' }
        		],
        		PWD: [{ 
        			validator: v_pwd1, trigger: 'blur' }
        		],
        		CK_PWD:[{ 
        			validator: v_pwd2, trigger: 'blur' }
        		]
        	},
        	// 授权管理
        	user_client_show:false,
        	client_info:[],
        	user_client:[],
        	user_client_:[],
        	op_user_id:'',
        	
        	// 应用管理
        	ld_client_url:'{0}/client/getClient'.format(_AppRootContext),
        	ld_client_url_:'{0}/client/getClient'.format(_AppRootContext),
        	client_search:{kw:''},
        	client_show:false,
        	client_optype:1,
        	client_data:{},
        	client_rules:{
        		CLIENTID: [
                    { required: true, message: '请输入CLIENTID', trigger: 'blur' },
                ],
                TITLE:[{required:true,message:'请输入应用名',trigger:'blur'}],
                ICON:[{required:true,message:'请输入图标',trigger:'blur'}],
                STATE:[{validator:function(r,v,c){
                	if(v!==0 && v!==1){
                		c(new Error('状态不合法'))
                	}
                	c();
                },trigger:'blur'}],
                RDURL:[{required:true,message:'请输入跳转URL',trigger:'blur'}],
                SECRET:[{required:true,message:'请输入秘钥',trigger:'blur'}],
        	}
         }
 	},
     mounted:function(){
     	this.loadApps();
     },
     methods:{
    	 save_client:function(){
    		var self=this;
    		this.$refs.client_form.validate(function(v){
    			if(!v) return;
    			var fd = new FormData();
     			for(var k in self.client_data){
     				if(['CLIENTID','ICON','RDURL','SECRET','STATE','TITLE'].includes(k)){
     					fd.append(k.toLowerCase(),self.client_data[k])
     				}
     			}
     			fd.append('optype',self.client_optype);
     			self.op_posting=true;
     			axios({
     				url:'{0}/client/saveClient'.format(_AppRootContext),
     				method:'POST',
     				data:fd
     			}).then(function(res){
     				self.op_posting=false;
     				if(res.data.code==200){
     					self.$message({
     						type:'success',
     						message:'操作成功'
     					})
     					self.client_show = false;
     					self.$refs.client_table.reload();
     				}else{
     					self.$message({
     						type:'error',
     						message:res.data.msg
     					});
     				}
     			}).catch(function(err){
     				self.op_posting=false;
     				console.log(err);
     			});
    		});
    	 },
    	 delete_client:function(row){
    		var self=this;   
      		this.$confirm('确定要删除吗?', '提示', {
      	    	confirmButtonText: '确定',
      	        cancelButtonText: '取消',
     	        type: 'warning'
      	   	}).then(() => {
      	   		
      	   		self.op_posting=true;
          		axios({
      				url:'{0}/client/deleteClient'.format(_AppRootContext),
      				method:'POST',
      				data:{id:row.ID}
      			}).then(function(res){
      				self.op_posting=false;
      				if(res.data.code==200){
      					self.$message({
      						type:'success',
      						message:'删除成功'
      					})
      					self.$refs.client_table.reload();
      				}else{
      					self.$message({
      						type:'error',
      						message:res.data.msg
      					});
      				}
      			}).catch(function(err){
      				self.op_posting=false;
      				console.log(err);
      			});
      	   	}).catch(() => {
      	   		// cancel
      	   	});
    	 },
    	 show_client_edit:function(row){
    		 console.log(row)
    		this.client_show=true;
    		var tmp={};
    		for(var k in row){
    			tmp[k] = row[k];
    		}
     		this.client_data=tmp;
     		this.client_optype=2;
    	 },
    	 show_client_add:function(){
    		this.client_show=true;
    		this.client_data={STATE:0};
    		this.client_optype=1;
    	 },
    	 btn_client_search:function(){
    		 this.ld_client_url = "{0}?kw={1}".format(this.ld_client_url_,this.client_search.kw);
    	 },
     	all_clients:function(){				
     		if(this.client_info.length>0){
     			return;
     		}
     		var self=this;
     		axios({
 				url:'{0}/client/allClients'.format(_AppRootContext),
 				method:'get'
 			}).then(function(res){
 				if(res.data.code==200){
						var dt = res.data.data;
						for(var i=0;i<dt.length;i++){
							dt[i].key = dt[i].clientid;
							dt[i].label = dt[i].title;
						}
						self.client_info = dt;
 				}else{
 					self.$message({
 						type:'error',
 						message:res.data.msg
 					});
 				}
 			}).catch(function(err){
 				console.log(err);
 			}); 
     	},
     	user_client_info:function(){
     		if(!this.op_user_id) return;
     		var self=this;
     		axios({
 				url:'{0}/user/getUserClient?userId={1}'.format(_AppRootContext,this.op_user_id),
 				method:'get'
 			}).then(function(res){
 				if(res.data.code==200){
 					var dt = res.data.data;
 					var tmp=[];
 					for(var i=0;i<dt.length;i++){
 						tmp.push(dt[i].CLIENTID);
 					}
 					self.user_client_ = JSON.parse(JSON.stringify(tmp));
 					self.user_client = tmp;
 				}else{
 					self.$message({
 						type:'error',
 						message:res.data.msg
 					});
 				}
 			}).catch(function(err){
 				console.log(err);
 			}); 
     	},
     	show_user_client:function(row){
     		this.all_clients();
     		this.user_client_show = true;
     		this.op_user_id = row.XH;
     		this.user_client_info();
     	},
     	save_user_client:function(){
     		var orgin = this.user_client_;
     		var cli = this.user_client;
     		
     		var add_cli = cli.filter(function(id){
     			return !orgin.includes(id);
     		});
     		var del_cli = orgin.filter(function(id){
     			return !cli.includes(id);
     		});
     		
     		var self=this;
     		self.op_posting=true;
     		axios({
 				url:'{0}/user/saveUserClient'.format(_AppRootContext),
 				method:'POST',
 				data:{
 					userId:this.op_user_id,
 					add_cli:add_cli,
 					del_cli:del_cli
 				}
 			}).then(function(res){
 				self.op_posting=false;
 				if(res.data.code==200){
 					self.$message({
 						type:'success',
 						message:'操作成功'
 					})
 					self.apps=[];
 					self.user_client_show = false;
 				}else{
 					self.$message({
 						type:'error',
 						message:res.data.msg
 					});
 				}
 			}).catch(function(err){
 				self.op_posting=false;
 				console.log(err);
 			});
     		
     	},
     	import_template:function(){
     		window.location.href="{0}/doc/用户导入.xlsx".format(_AppRootContext);
     	},
     	import_user:function(){	
     		var self=this;
     		var file = this.$refs.user_file;
     		
     		
     		var change = function(){
     			if(this.files.length==0){
     				return;
     			}
     			
     			var fd = new FormData();
     			fd.append('file',this.files[0]);
     			self.op_posting=true;
     			axios({
     				url:'{0}/user/importUser'.format(_AppRootContext),
     				method:'POST',
     				data:fd
     			}).then(function(res){
     				self.op_posting=false;
     				if(res.data.code==200){
     					self.$message({
     						type:'success',
     						message:'成功'
     					});
     					self.$refs.user_table.reload();
     				}else{
     					self.$message({
     						type:'error',
     						message:res.data.msg
     					});
     				}
     			}).catch(function(err){
     				self.op_posting=false;
     				console.log(err);
     			});                      	
             };
     		
     		
     		file.removeEventListener("change",change);
     		file.value='';
     		file.addEventListener('change',change);
     		file.click();
     	},
     	reset_pwd:function(row){
     		this.reset_pwd_data.userId = row.XH;
     		this.reset_pwd_data.pwd='';
     		this.reset_pwd_show=true;
     	},
     	save_reset_pwd:function(row){
     		var self=this;
     		
     		
     		this.$refs.reset_pwd_form.validate(function(v){
     			if(!v) return;
     			self.$confirm('确定要重置吗?', '提示', {
         	    	confirmButtonText: '确定',
         	        cancelButtonText: '取消',
        	        	type: 'warning'
         	   	}).then(() => {
             		self.op_posting=true;
             		axios({
         				url:'{0}/user/resetPwd'.format(_AppRootContext),
         				method:'POST',
         				data:{
         					id:self.reset_pwd_data.userId,
         					pwd:self.reset_pwd_data.pwd
         				}
         			}).then(function(res){
         				self.op_posting=false;
         				if(res.data.code==200){
         					self.$message({
         						type:'success',
         						message:'重置成功'
         					})
         					self.reset_pwd_show=false;
         				}else{
         					self.$message({
         						type:'error',
         						message:res.data.msg
         					});
         				}
         			}).catch(function(err){
         				self.op_posting=false;
         				console.log(err);
         			});
         	   	}).catch(() => {
         	   		// cancel
         	   	});	
     		})
     	},
     	delete_user:function(row){
     		var self=this;   
     		
     		this.$confirm('确定要删除吗?', '提示', {
     	    	confirmButtonText: '确定',
     	        cancelButtonText: '取消',
    	        	type: 'warning'
     	   	}).then(() => {
     	   		
     	   		self.op_posting=true;
         		axios({
     				url:'{0}/user/deleteUser'.format(_AppRootContext),
     				method:'POST',
     				data:{id:row.XH}
     			}).then(function(res){
     				self.op_posting=false;
     				if(res.data.code==200){
     					self.$message({
     						type:'success',
     						message:'删除成功'
     					})
     					self.$refs.user_table.reload();
     				}else{
     					self.$message({
     						type:'error',
     						message:res.data.msg
     					});
     				}
     			}).catch(function(err){
     				self.op_posting=false;
     				console.log(err);
     			});
     	   	}).catch(() => {
     	   		// cancel
     	   	});
     		
     	},
     	show_user_edit:function(row){
     		this.user_show = true;
     		var tmp={};
     		for(var k in row){
     			tmp[k] = row[k];	
     		}
     		this.user_data= tmp;
     		this.user_optype=2;
     	},
     	show_user_add:function(){
     		this.user_show = true;
     		this.user_data={XB:0,LX:1};
     		this.user_optype=1;
     	},
     	save_user:function(){
     		var self=this;
     		this.$refs.user_form.validate(function(v){
     			if(!v) return;
     			var fd = new FormData();
     			for(var k in self.user_data){
     				if(k=='CK_PWD'){
     					continue;
     				}else{
         				fd.append(k.toLowerCase(),self.user_data[k])
     				}
     			}
     			fd.append('optype',self.user_optype);
     			self.op_posting=true;
     			axios({
     				url:'{0}/user/saveUser'.format(_AppRootContext),
     				method:'POST',
     				data:fd
     			}).then(function(res){
     				self.op_posting=false;
     				if(res.data.code==200){
     					self.$message({
     						type:'success',
     						message:'操作成功'
     					})
     					self.user_show = false;
     					self.$refs.user_table.reload();
     				}else{
     					self.$message({
     						type:'error',
     						message:res.data.msg
     					});
     				}
     			}).catch(function(err){
     				self.op_posting=false;
     				console.log(err);
     			});
     		})
     	},
     	btn_user_search:function(){
     		this.ld_user_url = "{0}?lx={1}&kw={2}".format(this.ld_user_url_,this.user_search.lx,this.user_search.kw);
     	},
     	handleSelect:function(n){
     		this.active_mode=n;
     		this.$nextTick(function(){
         		if(n=='me'){
         			if(!this.apps || this.apps.length==0){
         				this.loadApps();
         			}
         		}else if(n=='all_client'){
         			if(!this.all_apps || this.all_apps.length==0){
         				this.loadAllApps();
         			}
         		}else if(n=='app_manage'){
         			if(!this.$refs.client_table.loaded){
         				this.$refs.client_table.loaded=true;
         				this.$refs.client_table.loadData();
         			}
         		}else if(n=='user'){
         			if(!this.$refs.user_table.loaded){
         				this.$refs.user_table.loaded=true
         				this.$refs.user_table.loadData();
         			}
         		}
    		})
     	},
     	loadAllApps:function(){
     		var self = this;
            axios({
                url:"{0}/client/allClients".format(_AppRootContext),
                method:'GET',
            }).then(function(res){
                if(res.data.code==200){
                	var dt = res.data.data;
                	JSON.keyToLowerCase(dt)
                    var apps = [];
                    for(var i=0;i<dt.length;i++){
                        var item = dt[i];
                        var auth = '{0}/oauth2/authorize?response_type=code&client_id={1}&state=state&redirect_uri={2}'.format(_AppRootContext,item.clientid,item.rdurl)
                        apps.push({auth:auth,name:item.title,icon:item.icon});
                    }
                    self.all_apps = apps;
                 }else{
                 } 
            }).catch(function(err){
                console.log(err);
                self.error = "发生异常";
            });
     	},
         loadApps:function(){
             var self = this;
             axios({
                 url:"{0}/user/getMyClient".format(_AppRootContext),
                 method:'GET',
             }).then(function(res){
                 if(res.data.code==200){
                 	var dt = res.data.data;
                 	JSON.keyToLowerCase(dt)
                     var apps = [];
                     for(var i=0;i<dt.length;i++){
                         var item = dt[i];
                         var auth = '{0}/oauth2/authorize?response_type=code&client_id={1}&state=state&redirect_uri={2}'.format(_AppRootContext,item.clientid,item.rdurl)
                         apps.push({auth:auth,name:item.title,icon:item.icon});
                     }
                     self.apps = apps;
                  }else{
                  } 
             }).catch(function(err){
                 console.log(err);
                 self.error = "发生异常";
             });
         }
     }
 });